import { createHashHistory, createRouter, RouterProvider } from '@tanstack/react-router'
// Import the generated route tree
import { routeTree } from '@/routeTree.gen'
import { Err404 } from '@components/Err404'
import { useAuth } from '@hooks/useAuth'

// Create a new router instance
const router = createRouter({
  history: createHashHistory(),
  routeTree,
  defaultNotFoundComponent: () => <Err404 />,
  context: {
    auth: undefined,
  },
  beforeLoad: ({ context }) => {
    const { token } = context.auth || {}
    console.log('%c Line:17 🍓 token', 'color:#33a5ff', token)
  },
  beforeResolve: (route) => {
    console.log('beforeResolve', route)
  },
  afterResolve: (route) => {
    console.log('afterResolve', route)
  },
})

export function useAppRouter() {
  console.log('useAppRouter')
  const auth = useAuth()
  console.log('%c Line:26 🌶 auth', 'color:#fca650', auth)

  const AppRouterProvider = () => {
    return <RouterProvider router={router} context={{ auth }} />
  }

  return { AppRouterProvider }
}
